<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-input-number v-model="form.age" placeholder="请输入年龄" :precision="2"></el-input-number>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { ComponentSize, ElForm, FormInstance, FormRules } from 'element-plus'

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>()

// 表单数据
const form = ref({
  username: '',
  email: '',
  age: 10,
})

// 校验规则
const rules: FormRules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  age: [
    { required: true, message: '年龄不能为空', trigger: 'blur' },
    { type: 'number', min: 10, max: 20, message: '年龄在 10~20', trigger: 'blur' },
  ],
}

// 提交处理函数
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 如果校验通过，直接提交
      submitForm()
    } else {
      // 如果校验未通过，弹出确认框
      ElMessageBox.confirm('表单校验未通过，是否继续提交？', '提示', {
        confirmButtonText: '继续提交',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 用户确认后，强制提交
          submitForm()
        })
        .catch(() => {
          // 用户取消，不做任何操作
          ElMessage.info('已取消提交')
        })
    }
  })
}

// 提交逻辑
const submitForm = () => {
  // 模拟提交逻辑
  ElMessage.success('表单已提交')
  console.log('提交的数据:', form.value)
}
</script>
